/* $RCSFile: ContactsEdit.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Contacts/ContactsEdit.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:46  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Security;
using AddonNice.Helpers;
using AddonNice.UI;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Settings.PageModules.Contacts;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Contacts
{
    public partial class ContactsEdit : AddEditItemPage
    {
        ContactsDB contactsDB   =   new ContactsDB();

        string _PathToSave      =   string.Empty;
        public string PathToSave
        {
            get
            {
                if (string.IsNullOrEmpty(_PathToSave))
                {

                    SettingItem ob  =    moduleSettingsDic[CStr.MODULE_CONTACT_URL_IMAGES];
                    if (ob != null)
                    {
                        _PathToSave =   Server.MapPath(ob.FullPath) + "\\";
                        //Make sure the target directory exists
                        if (!System.IO.Directory.Exists(_PathToSave))
                        {
                            try
                            {
                                System.IO.Directory.CreateDirectory(_PathToSave);
                            }
                            catch (Exception ex)
                            {
                                if (PageTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactsEdit PathStoSave : {0}, ex :{1}", _PathToSave, ex),PageTraceSwitch.Sw.Info);
                            }
                        }
                    }
                }
                return _PathToSave;
            }
        }

        public ContactsEdit() : base(true, true, true, true)
        { 
        }

        /// <summary>
		/// The Page_Load event on this Page is used to obtain the ModuleID
		/// and ItemID of the contact to edit.
		/// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
            // If the page is being requested the first time, determine if an
            // contact itemID value is specified, and if so populate page
            // contents with the contact details
            if (!IsPostBack) 
            {
                if ( !isNewItem ) 
                {
                    // Obtain a single row of contact information
                    SqlDataReader dr                =   null;
					try
					{
						dr	                        =	contactsDB.GetSingleContactGlobalized(ItemID);
                
						if(dr.Read())
						{
							NameField.Text          =   (dr["Name"] == DBNull.Value) ? string.Empty : (string) (dr["Name"]);
							RoleField.Text          =   (dr["Role"] == DBNull.Value) ? string.Empty : (string) (dr["Role"]);
							EmailField.Text         =   (dr["Email"] == DBNull.Value) ? string.Empty : (string) (dr["Email"]);
							Contact1Field.Text      =   (dr["Contact1"] == DBNull.Value) ? string.Empty : (string) (dr["Contact1"]);
							Contact2Field.Text      =   (dr["Contact2"] == DBNull.Value) ? string.Empty : (string) (dr["Contact2"]);
							FaxField.Text           =   (dr["Fax"] == DBNull.Value) ? string.Empty : (string) (dr["Fax"]);
							AddressField.Text       =   (dr["Address"] == DBNull.Value) ? string.Empty : (string) (dr["Address"]);
							CreatedBy.Text          =   (dr["CreatedByUser"] == DBNull.Value) ? string.Empty : (string) (dr["CreatedByUser"]);
							CreatedDate.Text        =   (dr["CreatedDate"] == DBNull.Value) ? DateTime.Now.ToShortDateString() : ((DateTime) dr["CreatedDate"]).ToShortDateString();
							if (CreatedBy.Text == StStr.unknown || CreatedBy.Text == string.Empty )
							{
								CreatedBy.Text      =   LocalizeHelper.Localize ( StStr.UNKNOWN, StStr.unknown);
							}
						}
					}
					catch(Exception ex)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactsEdit Page_Load ex : {0}",ex),PageTraceSwitch.Sw.Info);
						throw;
					}
					finally
					{
						if ( dr != null )
							dr.Close();
					}                
				}
                else
                {
                }
            }
        }

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add ("2502DB18-B580-4F90-8CB4-C15E6E5339EF");
				return al;
			}
		}

		/// <summary>
		/// create or update a contact.  It  uses the AddonNice.ContactsDB()
		/// data component to encapsulate all data functionality.
		/// </summary>
        void ContactsEdit_Update(object sender, AddonNice.UI.ADNPageEventArgs e)
        {
            // Create an instance of the ContactsDB component
            string user = PortalSecurity.Wrapper.userName;
			try
			{
				if ( isNewItem ) 
				{
					Text2Image img	    =	new Text2Image();
					string strMail	    =	EmailField.Text.Trim();
					Bitmap imMail	    =	img.MakeImage(strMail);
					string imFileName	=	strMail.Replace('@','_').Replace('.','-');
					// save image to image folder with correct name
				    string PathThumbnail = PathToSave + imFileName+ ".gif";
					try
					{
						//Resize the original CRMImage with the given settings to create the thumbnail
						imMail.Save(PathThumbnail, System.Drawing.Imaging.ImageFormat.Gif);
					}
					catch (Exception ex)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactsEdit ContactsEdit_Update thumbnail.Save PathThumbnail : {0}, ex :{1}", PathThumbnail, ex),PageTraceSwitch.Sw.Info);
						throw;
					}
					finally
					{
						if ( imMail != null )
							imMail.Dispose();
					}
					// Add the contact within the contacts table
                    contactsDB.AddContact(ModuleID, ItemID, user, NameField.Text, RoleField.Text, EmailField.Text, Contact1Field.Text, Contact2Field.Text, FaxField.Text, AddressField.Text);
				}
				else 
				{
					// Update the contact within the contacts table
                    contactsDB.UpdateContactGlobalized(ModuleID, ItemID, user, NameField.Text, RoleField.Text, EmailField.Text, Contact1Field.Text, Contact2Field.Text, FaxField.Text, AddressField.Text);
				}
			}
			catch(Exception ex )
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactsEdit ContactsEdit_Update ex : {0}",ex),PageTraceSwitch.Sw.Info);
				throw;
			}
        }

		/// <summary>
		/// Delete a contact.  It  uses the AddonNice.ContactsDB()
		/// data component to encapsulate all data functionality.
		/// </summary>
        void ContactsEdit_Delete(object sender, AddonNice.UI.ADNPageEventArgs e)
        {

			// Only attempt to delete the item if it is an existing item
            if ( !isNewItem ) 
            {
				try
				{
					contactsDB.DeleteContactGlobalized(ItemID);
				}
				catch(Exception ex )
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactsEdit ContactsEdit_Delete ex : {0}",ex),PageTraceSwitch.Sw.Info);
                    throw;
				}
			}
		}

		#region Std overrides

        /// <summary>
        /// Here we create the command buttons and add them to the PlaceHolders prepared
        /// </summary>
        override protected void OnPreInit(EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ContactsEdit OnPreInit Begin",PageTraceSwitch.Sw.Info);
            if ( isNewItem ) 
                PageHasDeleteBtn    =   false;
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactsEdit OnPreInit PageHasDeleteBtn: {0}.",PageHasDeleteBtn),PageTraceSwitch.Sw.Info);
            base.OnPreInit(e);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ContactsEdit OnPreInit End",PageTraceSwitch.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
		{
            //Translate
            RequiredName.ErrorMessage = LocalizeHelper.Localize("CONTACTS_VALID_NAME");
            
			InitializeComponent();

			base.OnInit(e);
		}

        private void InitializeComponent() 
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ContactsEdit InitializeComponent Begin",PageTraceSwitch.Sw.Info);
			Load			+=	new EventHandler(Page_Load);
            Update          +=  new PageEventHandler(ContactsEdit_Update);
            Delete          +=  new PageEventHandler(ContactsEdit_Delete);
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ContactsEdit InitializeComponent End",PageTraceSwitch.Sw.Info);
		}

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons
        {
            get { return PlaceHolderButtons; }
            set { }
        }

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons2
        {
            get { return PlaceHolderButtons2; }
            set { }
        }
		#endregion
    }
}